﻿namespace Huioo.Learning.Agile.Payroll.Domain
{
    public class HourlyClassification : PaymentClassification
    {
        private readonly List<TimeCard> timeCards = new List<TimeCard>();
        private double hourlyRate;

        public HourlyClassification(double hourlyRate)
        {
            this.hourlyRate = hourlyRate;
        }

        public double HourlyRate { get; set; }

        public TimeCard GetTimeCard(DateTime dateTime)
        {
            throw new NotImplementedException();
        }

        internal void AddTimeCard(TimeCard timeCard)
        {
            timeCards.Add(timeCard);
        }


        public double CalculatePay(Paycheck paycheck)
        {
            double totalPay = 0.0;
            foreach (TimeCard timeCard in timeCards.Values)
            {
                if (IsInPayPeriod(timeCard, paycheck.PayDate))
                    totalPay += CalculatePayForTimeCard(timeCard);
            }
            return totalPay;
        }

        private bool IsInPayPeriod(TimeCard card,
                                        DateTime payPeriod)
        {
            DateTime payPeriodEndDate = payPeriod;
            DateTime payPeriodStartDate = payPeriod.AddDays(-5);
            return card.Date <= payPeriodEndDate &&
              card.Date >= payPeriodStartDate;
        }

        private double CalculatePayForTimeCard(TimeCard card)
        {
            double overtimeHours = Math.Max(0.0, card.Hours - 8);
            double normalHours = card.Hours - overtimeHours;
            return hourlyRate * normalHours +
              hourlyRate * 1.5 * overtimeHours;
        }

    }
}